<template>
  <view class="board">
    <view
      v-if="detail && detail.thumb"
      class="board-drawings"
    >
      <image
        :src="detail.thumb"
        mode="aspectFill"
      ></image>
    </view>
    <view class="board-paper">
      <canvas
        class="board-canvas"
        canvas-id="drawCanvas"
        disable-scroll="true"
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="touchEnd"
      ></canvas>
    </view>
    <view class="board-toolbar">
      <color-panel
        @colorPickTap="colorPickTapHandler"
        :colorPanelShow="colorPanelShow"
      ></color-panel>
      <toolbar
        :penColor="currentColor"
        @penWidthChange="penWidthChangeHandler"
        @toolItemTap="toolItemTapHandler"
        :toolArr="toolArr"
      ></toolbar>
      <comm-fix-footer></comm-fix-footer>
    </view>
    <comm-beian></comm-beian>
    <comm-tabbar :show-tab-bar="showTabBar"></comm-tabbar>
  </view>
</template>

<script>
  import Toolbar from "./components/toolbar.vue";
  import ColorPanel from "./components/color-panel.vue";
  export default {
    name: "PainterIndex",
    components: {
      Toolbar,
      ColorPanel,
    },
    data() {
      return {
        showTabBar: false,
        detailId: "",
        detail: {},
        colorPanelShow: false,
        drawInfos: [],
        curDrawArr: [],
        startX: 0,
        startY: 0,
        drawContext: {},
        currentColor: "#091A22",
        begin: false,
        bgColor: "white",
        toolArr: [
          {
            title: "清空",
            icon: "../../static/images/painter/tool_clear.png",
            selectIcon: "../../static/images/painter/tool_clear_s.png",
            select: false,
            url: "clear",
          },
          {
            title: "橡皮",
            icon: "../../static/images/painter/tool_eraser.png",
            selectIcon: "../../static/images/painter/tool_eraser_s.png",
            select: false,
            url: "eraser",
          },
          {
            title: "画笔",
            icon: "../../static/images/painter/tool_pen.png",
            selectIcon: "../../static/images/painter/tool_pen_s.png",
            select: true,
            url: "pen",
          },
          {
            title: "颜色",
            icon: "../../static/images/painter/tool_color.png",
            selectIcon: "../../static/images/painter/tool_color_s.png",
            select: false,
            url: "color",
          },
          {
            title: "保存",
            icon: "../../static/images/painter/tool_download.png",
            selectIcon: "../../static/images/painter/tool_download_s.png",
            select: false,
            url: "save",
          },
          {
            title: "矩形",
            icon: "../../static/images/painter/tool_rect.png",
            selectIcon: "../../static/images/painter/tool_rect_s.png",
            select: false,
            url: "hollowRect",
          },
          {
            title: "圆形",
            icon: "../../static/images/painter/tool_circle.png",
            selectIcon: "../../static/images/painter/tool_circle_s.png",
            select: false,
            url: "hollowCircle",
          },
          {
            title: "矩形",
            icon: "../../static/images/painter/tool_rect_solid.png",
            selectIcon: "../../static/images/painter/tool_rect_solid_s.png",
            select: false,
            url: "rect",
          },
          {
            title: "圆形",
            icon: "../../static/images/painter/tool_circle_solid.png",
            selectIcon: "../../static/images/painter/tool_circle_solid_s.png",
            select: false,
            url: "circle",
          },
          {
            title: "分享",
            icon: "../../static/images/painter/tool_share.png",
            selectIcon: "../../static/images/painter/tool_share_s.png",
            select: false,
            url: "share",
          },
        ],
        lineWidth: 6,
        penMode: true,
        rectMode: false,
        hollowRectMode: false,
        circleMode: false,
        hollowCircleMode: false,
        lastHollowRect: {},
        lastHollowCircle: {},
      };
    },
    onLoad(options) {
      this.detailId = options.id;
    },
    onShow() {
      console.log("PainterIndex页面加载成功", uni.getStorageSync("detail_id"));
      let detailId = this.detailId || uni.getStorageSync("detail_id");
      if (detailId) {
        this.detailId = detailId;
      }
      console.log("detailId", detailId);
      // 从this.$config.demo.list中获取数据

      this.drawContext = uni.createCanvasContext("drawCanvas");
      this.initBoard();
      this.$nextTick(() => {
        this.fillBackground(this.drawContext);
        console.log("this.detail", detailId, !detailId);
        if (!detailId) {
          this.showTabBar = true;
        }
        this.getDetail();
      });
    },
    methods: {
      getDetail() {
        console.log("~!~~~detailId", this.detailId);
        if (!this.detailId) {
          return;
        }
        console.log("~!~~~detailId~~", this.detailId);
        this.$request({
          url: "/detail/" + this.detailId + ".json",
          method: "GET",
        }).then((res) => {
          console.log("detail.json", res);
          this.detail = res;
          this.category = this.$config.demo.category.find(
            (item) => item.id == this.detail.category_id,
          );
          console.log(" this.detail", this.detail);
          uni.setNavigationBarTitle({
            title: this.detail.name + " - 简笔画画法",
          });

          uni.setNavigationBarTitle({
            title: `画 ${this.detail.name} - 简笔画画板`,
          });
        });
      },
      colorPickTapHandler(obj) {
        console.log("我点击的颜色:", obj);
        this.colorPanelShow = false;
        this.toolArr.forEach((item) => {
          item.select = false;
          if (item.title === "画笔") {
            item.select = true;
          }
        });
        this.rectMode = false;
        this.hollowRectMode = false;
        this.circleMode = false;
        this.hollowCircleMode = false;
        this.penMode = true;
        this.currentColor = obj.color;
        this.drawContext.strokeStyle = obj.color;
      },
      penWidthChangeHandler(width) {
        this.lineWidth = width;
        console.log("画笔宽度:", width);
        this.drawContext.setLineWidth(width);
      },
      toolItemTapHandler(index) {
        const that = this;
        let url = this.toolArr[index]["url"];
        switch (url) {
          case "clear":
            this.clearDrawBoard();
            break;
          case "eraser":
            this.drawContext.strokeStyle = this.bgColor;
            this.colorPanelShow = false;
            break;
          case "pen":
            this.drawContext.strokeStyle = this.currentColor;
            this.colorPanelShow = false;
            this.rectMode = false;
            this.hollowRectMode = false;
            this.circleMode = false;
            this.hollowCircleMode = false;
            this.penMode = true;
            break;
          case "color":
            this.colorPanelShow = !this.colorPanelShow;
            // this.drawMode = this.colorPanelShow ? false : true;
            break;
          case "save":
            break;
          case "hollowRect":
            this.hollowRectMode = true;
            this.rectMode = false;
            this.circleMode = false;
            this.hollowCircleMode = false;
            this.penMode = false;
            this.colorPanelShow = false;
            this.drawContext.strokeStyle = this.currentColor;
            // this.drawContext.restore();
            break;
          case "hollowCircle":
            this.hollowRectMode = false;
            this.rectMode = false;
            this.circleMode = false;
            this.hollowCircleMode = true;
            this.penMode = false;
            this.colorPanelShow = false;
            this.drawContext.strokeStyle = this.currentColor;
            break;
          case "rect":
            this.hollowRectMode = false;
            this.rectMode = true;
            this.circleMode = false;
            this.hollowCircleMode = false;
            this.penMode = false;
            this.colorPanelShow = false;
            this.drawContext.strokeStyle = this.currentColor;
            break;
          case "circle":
            this.hollowRectMode = false;
            this.rectMode = false;
            this.circleMode = true;
            this.hollowCircleMode = false;
            this.penMode = false;
            this.colorPanelShow = false;
            this.drawContext.strokeStyle = this.currentColor;
            break;
          default:
            break;
        }
        if (url === "clear" || url === "save" || url === "share") {
          return;
        }
        this.toolArr.forEach((item, indexPath) => {
          item.select = false;
          if (indexPath === index) {
            item.select = true;
          }
        });
      },
      clearDrawBoard() {
        this.initBoard();
        this.fillBackground(this.drawContext);
      },
      initBoard() {
        this.drawContext.setLineCap("round"); // 让线条圆润
        this.drawContext.strokeStyle = this.currentColor;
        this.drawContext.setLineWidth(this.lineWidth);
      },
      touchStart(e) {
        console.log("我能够进行绘制");
        if (this.penMode) {
          this.lineBegin(e.touches[0].x, e.touches[0].y);
        } else if (this.rectMode) {
          this.rectBegin(e.touches[0].x, e.touches[0].y);
        } else if (this.hollowRectMode) {
          this.hollowRectBegin(e.touches[0].x, e.touches[0].y);
        } else if (this.hollowCircleMode) {
          this.hollowCircleBegin(e.touches[0].x, e.touches[0].y);
        } else if (this.circleMode) {
          this.circleBegin(e.touches[0].x, e.touches[0].y);
        }
        this.curDrawArr.push({
          x: e.touches[0].x,
          y: e.touches[0].y,
        });
      },
      touchMove(e) {
        if (this.begin) {
          if (this.penMode) {
            this.lineAddPoint(e.touches[0].x, e.touches[0].y);
            this.draw(true);
          } else if (this.rectMode) {
            this.drawRect(e.touches[0].x, e.touches[0].y, true);
          } else if (this.hollowRectMode) {
            this.drawHollowRect(e.touches[0].x, e.touches[0].y, true);
          } else if (this.hollowCircleMode) {
            this.drawHollowCircle(e.touches[0].x, e.touches[0].y, true);
          } else if (this.circleMode) {
            this.drawCircle(e.touches[0].x, e.touches[0].y, true);
          }
          this.curDrawArr.push({
            x: e.touches[0].x,
            y: e.touches[0].y,
          });
        }
      },
      touchEnd(e) {
        // console.log('结束的坐标x:' + e.changedTouches[0].x + '结束的坐标y:' + e.changedTouches[0].y );
        if (this.penMode) {
          this.curDrawArr = [];
          this.lineEnd();
        } else if (this.rectMode) {
          this.drawRect(e.changedTouches[0].x, e.changedTouches[0].y, true);
        } else if (this.hollowRectMode) {
          this.drawHollowRect(e.changedTouches[0].x, e.changedTouches[0].y, true);
        } else if (this.hollowCircleMode) {
          this.drawHollowCircle(e.changedTouches[0].x, e.changedTouches[0].y, true);
        } else if (this.circleMode) {
          this.drawCircle(e.changedTouches[0].x, e.changedTouches[0].y, true);
        }
      },
      hollowRectBegin(x, y) {
        this.begin = true;
        this.drawContext.beginPath();
        this.startX = x;
        this.startY = y;
      },
      rectBegin(x, y) {
        this.begin = true;
        this.drawContext.beginPath();
        this.startX = x;
        this.startY = y;
      },
      hollowCircleBegin(x, y) {
        this.begin = true;
        this.drawContext.beginPath();
        this.startX = x;
        this.startY = y;
      },
      circleBegin(x, y) {
        this.begin = true;
        this.drawContext.beginPath();
        this.startX = x;
        this.startY = y;
      },
      /**
       * 这里是画实体矩形
       */
      drawRect(x, y, isReverse) {
        let width = x - this.startX ? x - this.startX : this.startX - x;
        let height = y - this.startY ? y - this.startY : this.startY - y;
        this.drawContext.rect(this.startX, this.startY, width, height);
        this.drawContext.setFillStyle(this.currentColor);
        this.drawContext.fill();
        this.draw(isReverse);
      },
      /**
       * 这里是画空心矩形
       * 方法是根据四个坐标点画
       * 四条线进行连接
       */
      drawHollowRect(x, y, isReverse) {
        let pointLT = {};
        let pointRB = {};
        let pointRT = {};
        let pointLB = {};
        let center = {};

        pointLT.X = this.startX <= x ? this.startX : x;
        pointLT.Y = this.startY <= y ? this.startY : y;

        pointRB.X = this.startX >= x ? this.startX : x;
        pointRB.Y = this.startY >= y ? this.startY : y;

        pointRT.X = pointRB.X;
        pointRT.Y = pointLT.Y;

        pointLB.X = pointLT.X;
        pointLB.Y = pointRB.Y;

        let width = x - this.startX ? x - this.startX : this.startX - x;
        let height = y - this.startY ? y - this.startY : this.startY - y;
        this.drawContext.rect(this.startX, this.startY, width, height);
        this.drawContext.setStrokeStyle(this.currentColor);
        this.drawContext.stroke();
        this.draw(isReverse);

        this.lastHollowRect = {
          x: this.startX,
          y: this.startY,
          width: Math.abs(width),
          height: Math.abs(height),
          pointLT: pointLT,
        };
        this.clearLastHollowRect();
      },
      clearLastHollowRect() {
        console.log("上一个矩形对象:", this.lastHollowRect);
        this.drawContext.clearRect(
          this.lastHollowRect.pointLT.X + this.lineWidth / 2,
          this.lastHollowRect.pointLT.Y + this.lineWidth / 2,
          this.lastHollowRect.width - this.lineWidth,
          this.lastHollowRect.height - this.lineWidth,
        );
      },
      clearLastHollowCircle(x, y, r, cxt) {
        //(x,y)为要清除的圆的圆心，r为半径，cxt为context
        var stepClear = 1; //别忘记这一步
        clearArc(x, y, r);

        function clearArc(x, y, radius) {
          var calcWidth = radius - stepClear;
          var calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);

          var posX = x - calcWidth;
          var posY = y - calcHeight;

          var widthX = 2 * calcWidth;
          var heightY = 2 * calcHeight;

          if (stepClear <= radius) {
            cxt.clearRect(posX, posY, widthX, heightY);
            stepClear += 1;
            clearArc(x, y, radius);
          }
        }
      },
      /**
       * 这里是画
       * 实心圆
       */
      drawCircle(x, y, isReverse) {
        let pointLT = {};
        let pointRB = {};
        let pointRT = {};
        let pointLB = {};
        let center = {};

        pointLT.X = this.startX <= x ? this.startX : x;
        pointLT.Y = this.startY <= y ? this.startY : y;

        pointRB.X = this.startX >= x ? this.startX : x;
        pointRB.Y = this.startY >= y ? this.startY : y;

        pointRT.X = pointRB.X;
        pointRT.Y = pointLT.Y;

        pointLB.X = pointLT.X;
        pointLB.Y = pointRB.Y;

        center.X = (pointRB.X + pointLT.X) / 2;
        center.Y = (pointRB.Y + pointLT.Y) / 2;

        let dx = pointRB.X - pointLT.X;
        let dy = pointRB.Y - pointLT.Y;
        let r = Math.sqrt(dx * dx + dy * dy) / 2;

        // console.log('圆心坐标:' + JSON.stringify(center));
        // console.log('半径:' + JSON.stringify(r));
        this.drawContext.arc(center.X, center.Y, r, 0, 2 * Math.PI);
        this.drawContext.setFillStyle(this.currentColor);
        this.drawContext.fill();
        // this.drawContext.stroke();
        this.draw(isReverse);
      },
      /**
       * 这里是画
       * 空心圆
       */
      drawHollowCircle(x, y, isReverse) {
        let pointLT = {};
        let pointRB = {};
        let center = {};

        pointLT.X = this.startX <= x ? this.startX : x;
        pointLT.Y = this.startY <= y ? this.startY : y;

        pointRB.X = this.startX >= x ? this.startX : x;
        pointRB.Y = this.startY >= y ? this.startY : y;

        center.X = (pointRB.X + pointLT.X) / 2;
        center.Y = (pointRB.Y + pointLT.Y) / 2;

        let dx = pointRB.X - pointLT.X;
        let dy = pointRB.Y - pointLT.Y;
        let r = Math.sqrt(dx * dx + dy * dy) / 2;

        // console.log('圆心坐标:' + JSON.stringify(center));
        // console.log('半径:' + JSON.stringify(r));
        this.drawContext.arc(center.X, center.Y, r, 0, 2 * Math.PI);
        // this.drawContext.setFillStyle(this.currentColor);
        // this.drawContext.fill();
        this.drawContext.stroke();

        this.drawContext.beginPath();
        this.drawContext.arc(center.X, center.Y, r - this.lineWidth / 2, 0, 2 * Math.PI);
        this.drawContext.setFillStyle(this.bgColor);
        this.drawContext.fill();

        this.draw(isReverse);

        // this.clearLastHollowCircle(center.X, center.Y, r - this.lineWidth / 2, this.drawContext);
      },
      // 开始绘制线条
      lineBegin(x, y) {
        this.begin = true;
        this.drawContext.beginPath();
        this.startX = x;
        this.startY = y;
        this.drawContext.moveTo(this.startX, this.startY);
        this.lineAddPoint(x, y);
      },
      // 绘制线条中间添加点
      lineAddPoint(x, y) {
        this.drawContext.moveTo(this.startX, this.startY);
        this.drawContext.lineTo(x, y);
        this.drawContext.stroke();
        this.startX = x;
        this.startY = y;
      },
      // 绘制线条结束
      lineEnd() {
        this.drawContext.closePath();
        this.begin = false;
      },
      // canvas上下文设置背景为白色
      fillBackground(context) {
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".board-paper")
          .boundingClientRect((data) => {
            console.log("得到布局位置信息", data);
            context.setFillStyle(this.bgColor);
            //设置画布宽高
            context.width = data.width;
            context.height = data.height;
            context.fillRect(0, 0, data.width, data.height); //TODO context的宽和高待定
            context.fill();
            context.draw();
          })
          .exec();
      },
      // canvas上下文设置背景为白色
      fillWelcomeBackground(context) {
        const query = uni.createSelectorQuery().in(this);
        console.log("aaaaaaaaaaaaaaaaaa,dfg");
        query
          .select(".board-paper")
          .boundingClientRect((data) => {
            console.log("得到布局位置信息", data);
            context.setFillStyle(this.bgColor);
            context.fillRect(0, 0, data.width, data.height); //TODO context的宽和高待定
            context.fill();
            let pikaqiuW = 318;
            let pikaqiuH = 288;
            let pikaqiuX = (data.width - 318) / 2;
            let pikaqiuY = 80;
            context.drawImage("../../static/png/pikaqiu.png", pikaqiuX, pikaqiuY, 318, 288);

            // context.setFillStyle('#ff875d');
            // context.setFontSize(25);
            // context.setTextAlign('center');
            // context.fillText('很高兴见到你，', data.width / 2, 380)

            // context.setFillStyle('#ff875d');
            // context.setFontSize(25);
            // context.setTextAlign('center');
            // context.fillText('点击清空，开始你的创作吧！', data.width / 2, 420)

            // context.setTextAlign('center')
            // context.fillText('textAlign=center', 150, 80)

            // context.setTextAlign('right')
            // context.fillText('开始画画吧！', 150, 100)
            context.draw();
          })
          .exec();
      },
      // 绘制canvas
      // isReverse: 是否保留之前的像素
      draw(isReverse = false, cb) {
        this.drawContext.draw(isReverse, () => {
          if (cb && typeof cb == "function") {
            cb();
          }
        });
      },
    },
    //离开
    onUnload() {
      console.log("离开了画板");
      uni.removeStorageSync("detail_id");
    },
  };
</script>

<style lang="scss" scoped>
  .board {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    &-drawings {
      position: absolute;
      top: 120rpx;
      left: 20rpx;
      z-index: 2;
      width: 200rpx;
      height: 200rpx;
      background-color: #fff;
      border-radius: 20rpx;
      box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
      image {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }
    }
    &-paper {
      position: relative;
      z-index: 1;
      flex: 1 1 auto;
    }

    &-canvas {
      width: 100%;
      height: 100%;
    }
  }
</style>
